package com.yingxin.yxerp.module.dingtalk.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.yingxin.yx.framework.commons.constant.CommonConst;
import com.yingxin.yx.framework.commons.exception.BizException;
import com.yingxin.yxerp.module.dingtalk.config.WeComAppConfig;
import com.yingxin.yxerp.module.dingtalk.constant.WeComUrlConstant;
import com.yingxin.yxerp.module.dingtalk.dto.SendWeComWebHootTextDto;
import com.yingxin.yxerp.module.dingtalk.dto.msg.*;
import com.yingxin.yxerp.module.dingtalk.entity.WeComFileTypeEnums;
import com.yingxin.yxerp.module.dingtalk.entity.WeComMessageTypeEnums;
import com.yingxin.yxerp.module.dingtalk.service.WeComMessageNotificationService;
import com.yingxin.yxerp.module.dingtalk.util.SendWeComWebHootUtil;
import com.yingxin.yxerp.module.dingtalk.util.WeChatGroupMessage;
import com.yingxin.yxerp.module.dingtalk.util.WeComAccessTokenUtil;
import com.yingxin.yxerp.module.dingtalk.util.WeComFileUploadUtil;
import com.yingxin.yxerp.module.sys.entity.DingMessageSet;
import com.yingxin.yxerp.module.sys.service.IDingMessageSetService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.math.BigDecimal;

@Slf4j
@Service
public class WeComMessageNotificationServiceImpl implements WeComMessageNotificationService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WeComAppConfig appConfig;

    @Autowired
    private WeComAccessTokenUtil weComAccessTokenUtil;

    @Autowired
    private IDingMessageSetService dingMessageSetService;

    /**
     * 验证发送
     * @param chatType
     * @return chatId
     */
    private String checkSend( String chatType ){
        DingMessageSet set = dingMessageSetService.getDingMessageSetByType(chatType);
        if( ObjectUtil.isEmpty( set ) ){
            return null;
        }
        if( set.getIsSend().trim().equals( CommonConst.FALSE ) ){
            return null;
        }
        return set.getWeComChatId();
    }

    /**
     * 发送文件群消息
     */
    @Override
    public void sendGroupFileMsg(String filePath, String chatType) {
        // 上传图片素材
        String mediaId = uploadFile( filePath, WeComFileTypeEnums.FILE.getType() );
        if( StringUtils.isEmpty( mediaId ) ){
            throw new BizException("上传文件失败");
        }

        String chatId = checkSend( chatType );
        if( StringUtils.isEmpty( chatId ) ){
            return;
        }

        String requestUrl = WeComUrlConstant.SEND_GROUP_MSG + "?access_token="+getAccessToken();
        WeComMessageFile file = new WeComMessageFile();
        file.setChatid( chatId );
        file.setMsgtype( WeComMessageTypeEnums.file.getType() );
        file.setFile( new WeComMessageFileMedia( mediaId ) );
        file.setSafe( 0 );

        WeChatGroupMessage.sendMessage( file, requestUrl, restTemplate );
    }

    /**
     * 发送图片群消息
     */
    @Override
    public void sendGroupImgMsg(String filePath,String chatType){
        // 上传图片素材
        String mediaId = uploadFile( filePath, WeComFileTypeEnums.IMAGE.getType() );
        if( StringUtils.isEmpty( mediaId ) ){
            throw new BizException("上传文件失败");
        }

        String chatId = checkSend( chatType );
        if( StringUtils.isEmpty( chatId ) ){
            return;
        }

        String requestUrl = WeComUrlConstant.SEND_GROUP_MSG + "?access_token="+getAccessToken();
        WeComMessageImage image = new WeComMessageImage();
        image.setChatid( chatId );
        image.setMsgtype( WeComMessageTypeEnums.image.getType() );
        image.setImage( new WeComMessageImageMedia( mediaId ) );
        image.setSafe( 0 );

        WeChatGroupMessage.sendMessage( image, requestUrl, restTemplate );
    }

    /**
     * 发送群消息 - 文本
     */
    @Override
    public void sendGroupTextMsg(String content, String chatType) {
        String chatId = checkSend( chatType );
        if( StringUtils.isEmpty( chatId ) ){
            return;
        }

        String requestUrl = WeComUrlConstant.SEND_GROUP_MSG + "?access_token="+getAccessToken();
        WeComMessageText text = new WeComMessageText();
        text.setChatid( chatId );
        text.setMsgtype( WeComMessageTypeEnums.text.getType() );
        text.setText( new WeComMessageTextContent( content ) );
        text.setSafe( 0 );

        WeChatGroupMessage.sendMessage( text, requestUrl, restTemplate );
    }

    /**
     * 上传临时素材
     */
    @Override
    public String uploadFile(String filePath, String fileType) {
        File file = new File( filePath );
        BigDecimal fileMb = new BigDecimal( file.length() ).
                divide( new BigDecimal( 1024 * 1024 ) ).
                setScale(2, BigDecimal.ROUND_HALF_UP);

        if( WeComFileTypeEnums.IMAGE.getType().trim().equals( fileType ) ){
            if( fileMb.compareTo( new BigDecimal( 10 ) ) >= 0 ){
                throw new BizException("图片不得超出10Mb");
            }
        } else if( WeComFileTypeEnums.FILE.getType().trim().equals( fileType ) ){
            if( fileMb.compareTo( new BigDecimal(20 ) ) >= 0 ){
                throw new BizException("文件不得超出20Mb");
            }
        }

        String requestUrl = WeComUrlConstant.UPLOAD_MEDIA_URL + "?access_token=" + getAccessToken() + "&type=" + fileType;

        return WeComFileUploadUtil.upload( filePath, requestUrl );
    }

    /**
     * 获取 token
     */
    private String getAccessToken() {
        return weComAccessTokenUtil.getAccessToken(
                appConfig.getAppCorpId(), appConfig.getAppSecret());
    }

    /**
     * 调用企业微信webhoot发送文本信息
     */
    @Override
    public void sendWebHootTextMsg( String content ){
        SendWeComWebHootTextDto msg = new SendWeComWebHootTextDto();
        msg.setMsgtype( WeComMessageTypeEnums.text.getType() );
        msg.setText( new WeComMessageTextContent( content ) );
        SendWeComWebHootUtil.sendMessage( msg, restTemplate );
    }

}
